/**
 * 通用插件库 - 包含可复用的UI组件和功能
 */

/**
 * 基于dialog元素的模态框组件
 */
class DialogModal {
  /**
   * 创建模态框实例
   * @param {Object} options - 配置选项
   * @param {string} options.title - 模态框标题
   * @param {string} options.content - 正文内容
   * @param {string} options.type - 按钮类型 ('confirm' | 'action')
   * @param {string} options.confirmText - 确认按钮文字
   * @param {string} options.cancelText - 取消按钮文字
   * @param {string} options.actionText - 操作按钮文字
   * @param {string} options.actionType - 操作按钮类型 ('primary' | 'danger')
   * @param {Function} options.onConfirm - 确认回调
   * @param {Function} options.onCancel - 取消回调
   * @param {Function} options.onAction - 操作回调
   */
  constructor(options = {}) {
    this.options = {
      title: '提示',
      content: '',
      type: 'confirm', // 'confirm' | 'action'
      confirmText: '确认',
      cancelText: '取消',
      actionText: '操作',
      actionType: 'primary', // 'primary' | 'danger'
      onConfirm: null,
      onCancel: null,
      onAction: null,
      ...options
    };
    
    this.dialog = null;
    this.overlay = null;
    this.createModal();
  }
  
  /**
   * 创建模态框DOM结构
   */
  createModal() {
    // 创建遮罩层
    this.overlay = document.createElement('div');
    this.overlay.className = 'dialog-overlay';
    
    // 创建dialog元素
    this.dialog = document.createElement('dialog');
    this.dialog.className = 'dialog-modal';
    
    // 构建模态框内容
    this.dialog.innerHTML = `
      <div class="dialog-header">
        <h3 class="dialog-title">${this.options.title}</h3>
      </div>
      <div class="dialog-body">
        <p class="dialog-content">${this.options.content}</p>
      </div>
      <div class="dialog-footer">
        ${this.renderButtons()}
      </div>
    `;
    
    // 添加到页面
    document.body.appendChild(this.overlay);
    document.body.appendChild(this.dialog);
    
    // 绑定事件
    this.bindEvents();
    
    // 添加样式
    this.addStyles();
  }
  
  /**
   * 渲染按钮
   * @returns {string} 按钮HTML
   */
  renderButtons() {
    if (this.options.type === 'confirm') {
      return `<button class="dialog-btn dialog-btn-primary" data-action="confirm">${this.options.confirmText}</button>`;
    } else {
      const actionClass = this.options.actionType === 'danger' ? 'dialog-btn-danger' : 'dialog-btn-primary';
      return `
        <button class="dialog-btn dialog-btn-secondary" data-action="cancel">${this.options.cancelText}</button>
        <button class="dialog-btn ${actionClass}" data-action="action">${this.options.actionText}</button>
      `;
    }
  }
  
  /**
   * 绑定事件
   */
  bindEvents() {
    // 按钮点击事件
    this.dialog.addEventListener('click', (e) => {
      const action = e.target.dataset.action;
      if (action) {
        this.handleAction(action);
      }
    });
    
    // 遮罩层点击关闭（可选）
    this.overlay.addEventListener('click', () => {
      this.close();
    });
    
    // ESC键关闭
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && this.dialog.open) {
        this.close();
      }
    });
  }
  
  /**
   * 处理按钮操作
   * @param {string} action - 操作类型
   */
  handleAction(action) {
    switch (action) {
      case 'confirm':
        if (this.options.onConfirm) {
          this.options.onConfirm();
        }
        this.close();
        break;
      case 'cancel':
        if (this.options.onCancel) {
          this.options.onCancel();
        }
        this.close();
        break;
      case 'action':
        if (this.options.onAction) {
          this.options.onAction();
        }
        this.close();
        break;
    }
  }
  
  /**
   * 显示模态框
   */
  show() {
    this.overlay.classList.add('active');
    this.dialog.showModal();
    document.body.style.overflow = 'hidden';
  }
  
  /**
   * 关闭模态框
   */
  close() {
    this.overlay.classList.remove('active');
    this.dialog.close();
    document.body.style.overflow = '';
    
    // 延迟移除DOM元素
    setTimeout(() => {
      if (this.overlay && this.overlay.parentNode) {
        this.overlay.parentNode.removeChild(this.overlay);
      }
      if (this.dialog && this.dialog.parentNode) {
        this.dialog.parentNode.removeChild(this.dialog);
      }
    }, 300);
  }
  
  /**
   * 添加样式
   */
  addStyles() {
    if (document.getElementById('dialog-modal-styles')) {
      return;
    }
    
    const style = document.createElement('style');
    style.id = 'dialog-modal-styles';
    style.textContent = `
      .dialog-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 999;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
      }
      
      .dialog-overlay.active {
        opacity: 1;
        visibility: visible;
      }
      
      .dialog-modal {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        border: none;
        border-radius: 12px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        z-index: 1000;
        min-width: 320px;
        max-width: 500px;
        width: 90%;
        padding: 0;
        overflow: hidden;
      }
      
      .dialog-modal::backdrop {
        background: transparent;
      }
      
      .dialog-header {
        padding: 20px 24px 16px;
        border-bottom: 1px solid #e5e7eb;
        text-align: center;
      }
      
      .dialog-title {
        margin: 0;
        font-size: 14px;
        font-weight: 500;
        color: #8a8b8f;
      }
      
      .dialog-body {
        padding: 20px 24px;
        min-height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .dialog-content {
        margin: 0;
        font-size: 16px;
        line-height: 1.6;
        color: #3a3b3f;
        text-align: left;
        width: 100%;
      }
      
      /* 自定义内容模式 */
      .dialog-body.custom-content {
        display: block;
        text-align: center;
        padding: 20px;
      }
      
      .dialog-body.custom-content .dialog-content {
        display: none;
      }
      
      .dialog-body.custom-content .avatar-upload-dialog {
        margin: 0 auto;
        text-align: center;
      }
      
      .dialog-footer {
        padding: 16px 24px 20px;
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        border-top: 1px solid #e5e7eb;
      }
      
      .dialog-btn {
        padding: 8px 16px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        min-width: 80px;
      }
      
      .dialog-btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }
      
      .dialog-btn-primary:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }
      
      .dialog-btn-danger {
        background: #ef4444;
        color: white;
      }
      
      .dialog-btn-danger:hover {
        background: #dc2626;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
      }
      
      .dialog-btn-secondary {
        background: #f3f4f6;
        color: #6b7280;
        border: 1px solid #d1d5db;
      }
      
      .dialog-btn-secondary:hover {
        background: #e5e7eb;
        color: #4b5563;
      }
    `;
    
    document.head.appendChild(style);
  }
}

/**
 * 快捷方法：显示确认对话框
 * @param {string} title - 标题
 * @param {string} content - 内容
 * @param {Function} onConfirm - 确认回调
 * @returns {DialogModal} 模态框实例
 */
function showConfirmDialog(title, content, onConfirm) {
  const modal = new DialogModal({
    title,
    content,
    type: 'confirm',
    onConfirm
  });
  modal.show();
  return modal;
}

/**
 * 快捷方法：显示操作对话框
 * @param {string} title - 标题
 * @param {string} content - 内容
 * @param {Object} options - 选项
 * @param {string} options.actionText - 操作按钮文字
 * @param {string} options.actionType - 操作按钮类型
 * @param {Function} options.onAction - 操作回调
 * @param {Function} options.onCancel - 取消回调
 * @returns {DialogModal} 模态框实例
 */
function showActionDialog(title, content, options = {}) {
  const modal = new DialogModal({
    title,
    content,
    type: 'action',
    actionText: options.actionText || '确认',
    actionType: options.actionType || 'primary',
    onAction: options.onAction,
    onCancel: options.onCancel
  });
  
  // 如果内容包含avatar-upload-dialog，添加自定义样式类
  if (content.includes('avatar-upload-dialog')) {
    setTimeout(() => {
      const dialogBody = modal.dialog.querySelector('.dialog-body');
      if (dialogBody) {
        dialogBody.classList.add('custom-content');
        dialogBody.innerHTML = content;
      }
    }, 0);
  }
  
  modal.show();
  return modal;
}

/**
 * 快捷方法：显示删除确认对话框
 * @param {string} content - 内容
 * @param {Function} onConfirm - 确认删除回调
 * @returns {DialogModal} 模态框实例
 */
function showDeleteDialog(content, onConfirm) {
  return showActionDialog('确认删除', content, {
    actionText: '删除',
    actionType: 'danger',
    onAction: onConfirm
  });
}

/**
 * 气泡框组件
 */
class Tooltip {
  constructor() {
    this.tooltip = null;
    this.autoHideTimer = null;
    this.addStyles();
  }

  /**
   * 显示气泡框
   * @param {HTMLElement} target - 目标元素
   * @param {string} text - 提示文本
   * @param {string} position - 位置 ('top', 'bottom', 'left', 'right')
   * @param {number} autoHideDelay - 自动隐藏延迟时间（毫秒），默认2000ms
   */
  show(target, text, position = 'top', autoHideDelay = 2000) {
    this.hide(); // 先隐藏已存在的气泡框
    
    this.tooltip = document.createElement('div');
    this.tooltip.className = 'tooltip';
    this.tooltip.innerHTML = `
      <div class="tooltip-content">${text}</div>
      <div class="tooltip-arrow tooltip-arrow-${position}"></div>
    `;
    
    document.body.appendChild(this.tooltip);
    
    // 计算位置
    const targetRect = target.getBoundingClientRect();
    const tooltipRect = this.tooltip.getBoundingClientRect();
    
    let left, top;
    
    switch (position) {
      case 'top':
        left = targetRect.left + (targetRect.width - tooltipRect.width) / 2;
        top = targetRect.top - tooltipRect.height - 8;
        break;
      case 'bottom':
        left = targetRect.left + (targetRect.width - tooltipRect.width) / 2;
        top = targetRect.bottom + 8;
        break;
      case 'left':
        left = targetRect.left - tooltipRect.width - 8;
        top = targetRect.top + (targetRect.height - tooltipRect.height) / 2;
        break;
      case 'right':
        left = targetRect.right + 8;
        top = targetRect.top + (targetRect.height - tooltipRect.height) / 2;
        break;
    }
    
    // 确保气泡框不超出视窗
    left = Math.max(8, Math.min(left, window.innerWidth - tooltipRect.width - 8));
    top = Math.max(8, Math.min(top, window.innerHeight - tooltipRect.height - 8));
    
    this.tooltip.style.left = left + 'px';
    this.tooltip.style.top = top + 'px';
    
    // 添加显示动画
    setTimeout(() => {
      if (this.tooltip) {
        this.tooltip.classList.add('tooltip-show');
      }
    }, 10);
    
    // 设置自动隐藏定时器
    if (autoHideDelay > 0) {
      this.autoHideTimer = setTimeout(() => {
        this.hide();
      }, autoHideDelay);
    }
  }

  /**
   * 隐藏气泡框
   */
  hide() {
    // 清除自动隐藏定时器
    if (this.autoHideTimer) {
      clearTimeout(this.autoHideTimer);
      this.autoHideTimer = null;
    }
    
    if (this.tooltip) {
      this.tooltip.remove();
      this.tooltip = null;
    }
  }

  /**
   * 添加样式
   */
  addStyles() {
    if (document.getElementById('tooltip-styles')) return;
    
    const style = document.createElement('style');
    style.id = 'tooltip-styles';
    style.textContent = `
      .tooltip {
        position: fixed;
        z-index: 10000;
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 8px 12px;
        border-radius: 6px;
        font-size: 12px;
        line-height: 1.4;
        max-width: 200px;
        word-wrap: break-word;
        opacity: 0;
        transform: scale(0.8);
        transition: all 0.2s ease;
        pointer-events: none;
      }
      
      .tooltip.tooltip-show {
        opacity: 1;
        transform: scale(1);
      }
      
      .tooltip-content {
        position: relative;
        z-index: 1;
      }
      
      .tooltip-arrow {
        position: absolute;
        width: 0;
        height: 0;
        border: 6px solid transparent;
      }
      
      .tooltip-arrow-top {
        bottom: -12px;
        left: 50%;
        transform: translateX(-50%);
        border-top-color: rgba(0, 0, 0, 0.8);
      }
      
      .tooltip-arrow-bottom {
        top: -12px;
        left: 50%;
        transform: translateX(-50%);
        border-bottom-color: rgba(0, 0, 0, 0.8);
      }
      
      .tooltip-arrow-left {
        right: -12px;
        top: 50%;
        transform: translateY(-50%);
        border-left-color: rgba(0, 0, 0, 0.8);
      }
      
      .tooltip-arrow-right {
        left: -12px;
        top: 50%;
        transform: translateY(-50%);
        border-right-color: rgba(0, 0, 0, 0.8);
      }
    `;
    
    document.head.appendChild(style);
  }
}

// 创建全局气泡框实例
const globalTooltip = new Tooltip();

/**
 * 显示气泡框
 * @param {HTMLElement} target - 目标元素
 * @param {string} text - 提示文本
 * @param {string} position - 位置
 * @param {number} autoHideDelay - 自动隐藏延迟时间（毫秒），默认2000ms
 */
function showTooltip(target, text, position = 'top', autoHideDelay = 2000) {
  globalTooltip.show(target, text, position, autoHideDelay);
}

/**
 * 隐藏气泡框
 */
function hideTooltip() {
  globalTooltip.hide();
}

// 导出到全局
window.DialogModal = DialogModal;
window.showConfirmDialog = showConfirmDialog;
window.showActionDialog = showActionDialog;
window.showDeleteDialog = showDeleteDialog;
window.Tooltip = Tooltip;
window.showTooltip = showTooltip;
window.hideTooltip = hideTooltip;